﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace EvidenceWeb.Util
{
    public class InterfaceJsonConverter:JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType.IsInterface;
        }

        public override object ReadJson(JsonReader reader, Type objectType, JsonSerializer serializer)
        {
            Type t=null;

            string typeName = objectType.Name.Substring(1);
            string fullName = objectType.Namespace + "." + typeName;

            Assembly[] ambs = AppDomain.CurrentDomain.GetAssemblies();

            foreach (Assembly amb in ambs)
            {
                t = amb.GetType(fullName);
                if (t != null)
                    break;
            }

            if (t == null)
            {
                throw new Exception("接口"+objectType.Name+" 没有找到对应的实体类!");
            }

            object target=System.Activator.CreateInstance(t);

            serializer.Populate(reader, target);

            return target;

        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    }
}
